/*在线用户管理模块*/

#pragma once
#include <unordered_map>
#include <mutex>

#include "util.hpp"
using namespace ns_util;

class online_manager
{
private:
    /*游戏⼤厅的客⼾端连接管理*/
    std::unordered_map<uint64_t, wsserver_t::connection_ptr> _game_hall;
    /*游戏房间的客⼾端连接管理*/
    std::unordered_map<uint64_t, wsserver_t::connection_ptr> _game_room;
    std::mutex _mutex;

public:
    online_manager(){}
    /*进⼊游戏⼤厅--游戏⼤厅连接建⽴成功后调⽤*/
    void enter_game_hall(uint64_t uid, const wsserver_t::connection_ptr &conn)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        _game_hall.insert(std::make_pair(uid, conn));
    }

    /*退出游戏⼤厅--游戏⼤厅连接断开后调⽤*/
    void exit_game_hall(uint64_t uid)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        _game_hall.erase(uid);
    }

    /*进⼊游戏房间--游戏房间连接建⽴成功后调⽤*/
    void enter_game_room(uint64_t uid, const wsserver_t::connection_ptr &conn)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        _game_room.insert(std::make_pair(uid, conn));
    }

    /*退出游戏房间--游戏房间连接断开后调⽤*/
    void exit_game_room(uint64_t uid)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        _game_room.erase(uid);
    }

    /*判断⽤⼾是否在游戏⼤厅*/
    bool in_game_hall(uint64_t uid)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        auto it = _game_hall.find(uid);
        if (it == _game_hall.end())
        {
            return false;
        }
        return true;
    }

    /*判断⽤⼾是否在游戏房间*/
    bool in_game_room(uint64_t uid)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        auto it = _game_room.find(uid);
        if (it == _game_hall.end())
        {
            return false;
        }
        return true;
    }

    /*从游戏⼤厅中获取指定⽤⼾关联的Socket连接*/
    wsserver_t::connection_ptr get_con_from_game_hall(uint64_t uid)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        auto it = _game_hall.find(uid);
        if (it == _game_hall.end())
        {
            return wsserver_t::connection_ptr();
        }
        return it->second;
    }

    /*从游戏房间中获取指定⽤⼾关联的Socket连接*/
    wsserver_t::connection_ptr get_con_from_game_room(uint64_t uid)
    {
        std::unique_lock<std::mutex> lock(_mutex);
        auto it = _game_room.find(uid);
        if (it == _game_room.end())
        {
            return wsserver_t::connection_ptr();
        }
        return it->second;
    }
};